<template>
  <div>
    <v-tableTitle :btnConfig="btnConfig" :tableSelectData="tableSelectData" title="对接场景" @del="del" @newCreate="newCreate" @match="match" @resportConf="resportConf" @sqlConf="sqlConf" @clearAllStructure="clearAllStructure"></v-tableTitle>
    <GTable ref="table" :hasCheck="true" :hasEdit="true" :api="apiMap.getListApi" :columnSource="baseColumns" :cbFun="cbFun" @selection-change="data => tableSelectData = data"
      @setdialog="setdialog" />

    <el-dialog :title="dialogModule.title" :visible.sync="dialogModule.flag" center v-dialogDrag width="720px" @closed="closed">
      <div v-tit="'对接场景'">
        <GForm ref="detail" :config="formConfig" :rules="formRules" labelWidth="120px" v-model="form" @handleInput="handleInput"></GForm>
      </div>
      <span slot="footer">
        <el-button type="primary" @click="handleConfirm">确定</el-button>
        <el-button @click="dialogModule.flag = false">取消</el-button>
      </span>
    </el-dialog>

    <el-dialog title="对接场景测试" :visible.sync="dialogTableVisible" width="720px"> 
      <el-form ref="apitestformRef"  :model="apitestform">
    <el-form-item label="请求报文示例" :label-width="formLabelWidth">
      <el-input prop="apitestform.request" v-model="apitestform.request" type ="textarea" ></el-input>
    </el-form-item>
    <el-form-item label="响应信息" :label-width="formLabelWidth">
      <el-input prop="apitestform.response" v-model="apitestform.response" type ="textarea" disabled="true"></el-input>
    </el-form-item>
  </el-form>
    <div slot="footer" class="dialog-footer">
    <el-button @click="dialogTableVisible = false">取 消</el-button>
    <el-button type="primary" @click="sendTestRequest">请求</el-button>
  </div>
  </el-dialog>

  </div>
</template>

<script>
import tableTitle from 'commons/TableTitle'

export default {
  name: 'senece',
  data() {
    return {
      tableSelectData: [],
      dialogModule: {
        loading: false,
        flag: false,
        title: '',
        data: null,
        type: ''
      },
      form: {
        apiMappingCode:null,
        apiMappingName: null,
        applicationLinkId: '',
        applicationLinkDtlId: '',
        sourceApiId: '',
        targetApiId: '',
        remark: ''
      },
      apitestform:{
        request:'',
        response:''
      },
      options: {
        company: [],
        appLink: [],
        appLinkDtl: [],
        api: [],
        pickAppLinkDtl: [],
        expresscondition:[],
        activegatway:[]
      },
      dialogFormVisible:false,
      dialogTableVisible:false,
      currentid:null,
      formLabelWidth: '120px',
    }
  },
  computed: {
    btnConfig() {
      return [
        {
          label: this.$t('common.create'),
          invalid: 'newCreate'
        },
        {
          label: this.$t('common.delete'),
          disabled: true,
          invalid: 'del'
        },
        {
          label: '报文映射',
          disabled: true,
          invalid: 'match'
        },
        {
          label: '目标报文配置',
          disabled: true,
          invalid: 'resportConf'
        },
        {
          label: '对接场景测试',
          disabled: true,
          invalid: 'sqlConf'
        },
        {
          label: '清空报文映射信息',
          disabled: true,
          invalid: 'clearAllStructure'
        }
      ]
    },
    baseColumns() {
      return [
        {
          label: '对接场景编码',
          prop: 'apiMappingCode',
          input: 'input',
        },
        {
          label: '对接场景名称',
          prop: 'apiMappingName',
          input: 'input',
          width:'150px',
        },
        {
          label: '应用关联',
          prop: 'applicationLinkName',
          input: 'input'
        },
        {
          label: '应用环境',
          prop: 'applicationLinkDtlName',
          input: 'input'
        },
        {
          label: '源API',
          prop: 'sourceApiName',
          input: 'input'
        },
        {
          label: '目标API',
          prop: 'targetApiName',
          input: 'input'
        },
        {
          label: '生效API',
          prop: 'acivegatway',
          input: 'select',
          options: this.options.activegatway
        },
        {
          label: '外部请求URL',
          prop: 'externRequestUrl',
          input: 'input'
        },
        {
          label: '外部请求报文示例',
          prop: 'externRequestData',
          input: 'input'
        },
        {
          label: '备注',
          prop: 'remark'
        },
        {
          label: this.$t('app.addName'),
          prop: 'insUser'
        },
        {
          label: this.$t('app.addDate'),
          prop: 'insTime'
        },
        {
          label: this.$t('app.updateName'),
          prop: 'updUser'
        },
        {
          label: this.$t('app.updateDate'),
          prop: 'updTime'
        }
      ]
    },
    formConfig() {
      return [
        {
          label: '对接场景编码',
          prop: 'apiMappingCode',
          type: 'input'
        },
        {
          label: '对接场景名称',
          prop: 'apiMappingName',
          type: 'input'
        },
        {
          label: '应用关联',
          prop: 'applicationLinkId',
          type: 'select',
          options: this.options.appLink
        },
        {
          label: '应用环境',
          prop: 'applicationLinkDtlId',
          type: 'select',
          options: this.options.pickAppLinkDtl,
          disabled: data => !data.applicationLinkId
        },
        {
          label: '源API',
          prop: 'sourceApiId',
          type: 'select',
          options: this.options.api
        },
        {
          label: '目标API',
          prop: 'targetApiId',
          type: 'select',
          options: this.options.api
        },
        {
          label: '接口配置类型',
          prop: 'activeTarget',
          type: 'select',
          options:[
          { label: '', value: '' },
          { label: '字段映射调用目标接口', value: 'API' },
          { label: '字段映射生成插入语句', value: 'table' }]
        },
         {
          label: '生效API',
          prop: 'activegatway',
          type: 'select',
          options:this.options.activegatway
        },
        {
          label: '快递接口配置',
          prop: 'expresscondition',
          type: 'select',
          options:this.options.expresscondition
        },
        // {
        //   label: '更新数据生效规则',
        //   prop: 'preUpdActive',
        //   type: 'textarea',
        //   desc:'["校验规则名称"]'
        // },
        {
          label: '备注',
          prop: 'remark',
          type: 'textarea'
        }
      ]
    },
    formRules() {
      return {
        apiMappingName: [
          {
            required: true,
            message: '请输入对接场景名称',
            trigger: 'blur'
          }
        ],
        apiMappingCode: [
          {
            required: true,
            message: '请输入对接场景编码',
            trigger: 'blur'
          }
        ]
      }
    },
    apiMap() {
      return {
        getListApi: '/v1/edi/PlApiMapping/selectPlApiMappingList',
        getInfoApi: '/v1/edi/PlApiMapping/selectPlApiMappingById',
        deleteApi: '/v1/edi/PlApiMapping/deletePlApiMappingByIds',
        editApi: '/v1/edi/PlApiMapping/editPlApiMappingById',
        addApi: '/v1/edi/PlApiMapping/addPlApiMapping',
        clearAllStructure:'/v1/edi/PlApiMappingStructure/deleteStructureByMappingid',
        sendTestRequest:'/v1/edi/PlApiMapping/sendTestRequest',
      }
    }
  },
  methods: {
      sendTestRequest(){
      this.$post(this.apiMap.sendTestRequest, {
        id:this.currentid,
        request:this.apitestform.request
      }).then(res => {
        this.apitestform.response=res.data.item;
      })
    },
    match(data) {
      if(data.length != 1){
        return this.$message.error("请选择一条数据进行操作")
      }
      this.$router.push({ path: '/app/matchup', query: { id: data[0].id } })
    },
    resportConf(data){
      if(data.length != 1){
        return this.$message.error("请选择一条数据进行操作")
      }
      this.$router.push({ path: '/app/resportConf', query: { id: data[0].id } })
    },
    sqlConf(data){
      if(data.length != 1){
        return this.$message.error("请选择一条数据进行操作")
      }
      this.currentid = data[0].id;
      
      this.$post('/v1/edi/PlApiMapping/selectRequestSourceApi', {id:data[0].id}).then(res => {
        this.apitestform.request = res.data.item.apiRequestTemplate;
      });

      this.dialogTableVisible = true;
    },
    clearAllStructure(data){
      if(data.length != 1){
        return this.$message.error("请选择一条数据进行操作")
      }
      this.$confirm('是否清空所选记录配置报文映射?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        this.$post(this.apiMap.clearAllStructure, data).then(res => {
          this.$message.success(res.returnMgr)
          this.getTableData()
        })
      });
    },
    handleConfirm() {
      this.$refs.detail.validate().then(valid => {
        const params = this._.cloneDeep(this.form)
        const appObj = this.options.appLink.find(
          opt => opt.value == params.applicationLinkId
        )
        params.applicationLinkName = appObj.label
        const appDtlObj = this.options.pickAppLinkDtl.find(
          opt => opt.value == params.applicationLinkDtlId
        )
        params.applicationLinkDtlName = appDtlObj.linkName
        const sourceApiObj = this.options.api.find(
          opt => opt.value == params.sourceApiId
        )
        params.sourceApiName = sourceApiObj.apiName
        const targetApiObj = this.options.api.find(
          opt => opt.value == params.targetApiId
        )
        params.targetApiName = targetApiObj.apiName
        let promise
        if (this.dialogModule.type == 'edit') {
          promise = this.$post(this.apiMap.editApi, params)
        } else {
          promise = this.$post(this.apiMap.addApi, params)
        }
        promise.then(res => {
          this.$message.success(res.returnMgr)
          this.getTableData()
          this.$refs.detail?.resetFields()
          this.dialogModule.flag = false
        })
      })
    },
    handleInput(prop, val, obj) {
      if (prop == 'applicationLinkId') {
        this.$post('/v1/plApplicationLink/selectPlAppLinkDtlSelector', {
          id: val
        }).then(res => {
          this.options.pickAppLinkDtl = res.data.item.map(i => {
            i.label = i.linkName
            i.value = i.id
            return i
          })
        })
      }
    },
    getInfoById(id) {
      this.$post(this.apiMap.getInfoApi, {
        id
      }).then(res => {
        this.form = res.data.item
        this.dialogModule.flag = true
      })
    },
    setdialog(data) {
      this.dialogModule.title = `编辑[${data.apiMappingName}]对接场景`
      this.dialogModule.type = 'edit'
      this.dialogModule.data = data
      this.getInfoById(data.id)
    },
    newCreate() {
      this.dialogModule.title = '新增对接场景'
      this.dialogModule.type = 'add'
      this.dialogModule.data = null
      this.dialogModule.flag = true
      this.$refs.detail?.resetFields()
    },
    //删除
    async del(data) {
      this.$post(this.apiMap.deleteApi, data).then(res => {
        this.$message.success(res.returnMgr)
        this.getTableData()
      })
    },
    getOptions() {
      this.$post('/v1/plApplicationLink/selectPlAppLinkSelector').then(res => {
        const data = res.data.item
        this.options.appLink = data.map(i => {
          i.label = i.linkName
          i.value = i.id
          return i
        })
      })
      this.$post('/v1/plApplicationEnvironment/selectList', {
        pageNum: 1,
        pageSize: 999
      }).then(res => {
        const data = res.data.page.records
        this.options.appLinkDtl = data.map(i => {
          i.label = i.environmentName
          i.value = i.id
          return i
        })
      })
      this.$post('/v1/edi/apibaseinfo/selectPlApibaseinfoList', {
        pageNum: 1,
        pageSize: 999
      }).then(res => {
        const data = res.data.page.records
        this.options.api = data.map(i => {
          i.label = i.apiName
          i.value = i.id
          return i
        })
      });
      this.$post('/v1/edi/PlApiMapping/selectExpressConfigSelect', {}).then(res => {
        this.options.expresscondition = res.data.item;
      });

      this.$post('/v1/edi/PlApiMapping/selectActiveGatay', {}).then(res => {
        this.options.activegatway = res.data.item;
      })
    },
    closed() {
      this.$refs.detail?.resetFields()
    },
    cbFun(res) {
      return { list: res.data.page.records, total: res.data.page.total }
    },
    async getTableData() {
      this.$refs.table.getTableData()
    }
  },
  mounted() {
    this.getOptions()
  },
  components: {
    'v-tableTitle': tableTitle
  }
}
</script>

<style scoped>
</style>
